package com.example.blogdevelop.controller;


import cn.hutool.crypto.SecureUtil;
import com.example.blogdevelop.common.lang.Result;
import com.example.blogdevelop.entity.User;
import com.example.blogdevelop.service.MailService;
import com.example.blogdevelop.service.UserService;
import com.example.blogdevelop.vo.UserVo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;


    @Autowired
    private MailService mailService;

    @PostMapping("/sendEmail")
    @ResponseBody
    public Result sendEmail(@Validated @RequestBody String email, HttpSession httpSession) {
        log.info("email:{}", email);
        if(mailService.sendMimeMail(email, httpSession)){
            return Result.success();
        }
        return Result.fail();
    }

    @PostMapping("/regist")
    @ResponseBody
    public Result regist(@Validated @RequestBody UserVo userVo, HttpSession httpSession) {


        userVo.setCreated(LocalDateTime.now());
        userVo.setStatus(0);
        String password = userVo.getPassword();
        userVo.setPassword(SecureUtil.md5(password));
        userVo.setLastLogin(LocalDateTime.now());
        mailService.registered(userVo, httpSession);

        return Result.success();
    }

    @RequiresAuthentication
    @GetMapping("/index/{id}")
    public Result index(@PathVariable int id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

}
